﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;

namespace ProjectDanmaku.Util
{
    public static class MeshUtility
    {
#if UNITY_EDITOR
        private static Dictionary<string, int> _meshAllocCountDict = new Dictionary<string, int>();
#endif
        
        public static Mesh SpriteToMesh(Sprite sprite)
        {

#if UNITY_EDITOR
            if (!_meshAllocCountDict.TryAdd(sprite.name, 1))
            {
                if (_meshAllocCountDict[sprite.name]++ > 500)
                {
                    Debug.LogWarning(
                        "MeshUtility.SpriteToMesh was created more than 500 meshes for sprite " + sprite.name);
                }
            }
#endif
            
            Mesh mesh = new Mesh();
            
            Vector3[] vertices = new Vector3[sprite.vertices.Length];
            for (int i = 0; i < sprite.vertices.Length; i++)
            {
                vertices[i] = sprite.vertices[i];
            }
            
            int[] triangles = new int[sprite.triangles.Length];
            for (int i = 0; i < sprite.triangles.Length; i++)
            {
                triangles[i] = sprite.triangles[i];
            }
            
            mesh.vertices = vertices;
            mesh.uv = sprite.uv;
            mesh.triangles = triangles;
            
            mesh.name = "Mesh_" + sprite.name;

            return mesh;
        }
    }
}